package com.lagou.edu.filter;

import com.lagou.edu.service.TokenFeignClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;
import java.util.Set;

@Component  // 让容器扫描到，等同于注册了
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private TokenFeignClient tokenFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        URI uri = request.getURI();
        if(uri.getPath().contains("/user/info")) {
            // 合法请求，放行，执行后续的过滤器
            return chain.filter(exchange);
        }
        Set<String> strings = cookies.keySet();
        for (String string : strings) {
            List<HttpCookie> httpCookies = cookies.get(string);
            for (HttpCookie httpCookie : httpCookies) {
                String name = httpCookie.getName();
                if("token".equals(name)) {
                    String tokenValue = httpCookie.getValue();
                    //
                    String emailByToken = tokenFeignClient.getEmailByToken(tokenValue);
                    if(StringUtils.isNotBlank(emailByToken)) {
                        //重定向到首页
                        System.out.println("重定向到首页");
                        response.getHeaders().set("Location", "/static/welcome.html");
                        return exchange.getResponse().setComplete();
                    } else {
                        //未登录，重定向到登录页
                        System.out.println("重定向到登录页");
                        response.getHeaders().set("Location", "/static/login.html");
                        return exchange.getResponse().setComplete();
                    }
                }
            }
        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
